package com.leven.easyerp.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * DES加密工具类
 * 
 * @author Leven.Chen
 */
public class DESUtils {
	private static final String DEFAULT_KEY = "EERP_0428";

	/**
	 * 解密字符串
	 * 
	 * @param strIn
	 *            待解密的字符串
	 * @param strKey
	 *            密钥
	 * 
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String strIn, String strKey) throws Exception {
		if (strKey == null || strKey.trim().length() == 0) {
			strKey = DEFAULT_KEY;
		}
		/* 构建密钥对象 */
		DESKeySpec desKeySpec = new DESKeySpec(strKey.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(strKey.getBytes("UTF-8"));

		/* 构建解密器并初始化 */
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

		byte digest[] = new byte[strIn.length() / 2];
		for (int i = 0; i < digest.length; i++) {
			String byteString = strIn.substring(2 * i, 2 * i + 2);
			int byteValue = Integer.parseInt(byteString, 16);
			digest[i] = (byte) byteValue;
		}
		byte[] retBytes = cipher.doFinal(digest);
		return new String(retBytes);
	}

	/**
	 * 加密字符串
	 * 
	 * @param strIn
	 *            待加密的字符串
	 * @param strKey
	 *            密钥
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String strIn, String strKey) throws Exception {
		if (StringUtils.isEmpty(strKey)) {
			strKey = DEFAULT_KEY;
		}
		/* 构建密钥对象 */
		DESKeySpec desKeySpec = new DESKeySpec(strKey.getBytes("UTF-8"));
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(strKey.getBytes("UTF-8"));

		/* 构建加密器并初始化 */
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

		byte[] bytes = cipher.doFinal(strIn.getBytes("UTF-8"));

		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			String text = Integer.toHexString(0xff & bytes[i]);
			if (text.length() < 2) {
				text = "0" + text;
			}
			hexString.append(text.toUpperCase());
		}
		return hexString.toString();
	}
}
